package config

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"log"
	"net/url"
	"os"
	"time"
)

type config struct {
	Time struct {
		Start string `yaml:"start"`
		End   string `yaml:"end"`
	} `yaml:"time"`
	StartName []string `yaml:"start_name"`
	EndName   []string `yaml:"end_name"`
	Urls      []string `yaml:"urls"`
	Header    struct {
		ContentType   string `yaml:"content-type"`
		UserAgent     string `yaml:"user-agent"`
		Authorization string `yaml:"authorization"`
		Referer       string `yaml:"referer"`
	} `yaml:"header"`
	Log struct {
		ResultPath    string `yaml:"result_path"`
		ErrDetailPath string `yaml:"err_detail_path"`
	} `json:"log"`
}

func (c config) ValidateURLS() (urls []*url.URL) {
	for _, urlStr := range c.Urls {
		url, err := url.ParseRequestURI(urlStr)
		if err != nil {
			fmt.Println("地址格式错误：", urlStr, err.Error())
			os.Exit(1)
		}
		urls = append(urls, url)
	}
	return urls
}

func (c config) ParseStartTime() time.Time {
	timeParse, err := time.Parse(time.DateTime, c.Time.Start)
	if err != nil {
		fmt.Println("解析开始时间失败:", err.Error())
		os.Exit(1)
	}

	return timeParse
}

func (c config) ParseEndTime() time.Time {
	timeParse, err := time.Parse(time.DateTime, c.Time.End)
	if err != nil {
		fmt.Println("解析结束时间失败:", err.Error())
		os.Exit(1)
	}

	return timeParse
}

var C config

func init() {
	ParseYAML()
}

func ParseYAML() {
	file, err := os.ReadFile("./config/config.yml")
	if err != nil {
		log.Fatalln("读取配置文件失败：", err)
	}

	err = yaml.Unmarshal(file, &C)
	if err != nil {
		log.Fatalln("读取配置文件失败：", err)
	}
}
